package org.hbhk.hms.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.hbhk.hms.entity.HmsTopic;
import org.hbhk.hms.mq.MqProvider;
import org.hbhk.hms.mq.MqSender;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

@RestController
public class HmsTopicController {

	// 500kb
	private int lenMax = 524288;

	@Value("${mq.subscribe.HmsDelalyData:HmsDelalyData}")
	public String subscribe = "HmsDelalyData";

	@RequestMapping("/sendMsg")
	public Map<String, Object> sendMsg(@RequestBody List<HmsTopic> hmsTopics) {

		if (hmsTopics == null || hmsTopics.size() == 0) {
			return ResultUtils.getFaildResultData("parameter cannot be empty");
		}
		String json = JSON.toJSONString(hmsTopics);
		int len = json.getBytes().length;
		if (len > lenMax) {
			return ResultUtils.getFaildResultData("the single request parameter cannot be greater than 500kb");
		}
		// 校验字段
		for (HmsTopic hmsTopic : hmsTopics) {

			String mqName = hmsTopic.getMqName();
			if (StringUtils.isEmpty(mqName)) {
				return ResultUtils.getFaildResultData("mqName  cannot be empty");

			}
			if (!MqProvider.mqProducerCache.containsKey(mqName)) {
				return ResultUtils.getFaildResultData("mqName:" + mqName + "  does not exist");

			}
			String targetTopic = hmsTopic.getTargetTopic();

			if (StringUtils.isEmpty(targetTopic)) {
				return ResultUtils.getFaildResultData("targetTopic  cannot be empty");
			}

			String msg = hmsTopic.getMsg();

			if (StringUtils.isEmpty(msg)) {
				return ResultUtils.getFaildResultData("msg  cannot be empty");
			}

			String msgKey = hmsTopic.getMsgKey();

			if (StringUtils.isEmpty(msgKey)) {
				return ResultUtils.getFaildResultData("msgKey  cannot be empty");
			}

			Long delay = hmsTopic.getDelay();

			if (delay == null) {
				return ResultUtils.getFaildResultData("msgKey  cannot be empty");
			}
			String tags = hmsTopic.getTags();

			if (StringUtils.isEmpty(tags)) {
				hmsTopic.setTags("*");
			}

			hmsTopic.setCreateTime(new Date());
			hmsTopic.setDelayTime(new Date(hmsTopic.getDelay()));
			hmsTopic.setStatus(1);
		}
		MqSender.sendMessage(hmsTopics, MqProvider.hmsDelayMq, subscribe);
		return ResultUtils.getSuccessResultData();

	}

}
